const db = require('../config/db');
//引入加密模块
const bcrypt = require('bcryptjs');

const jwt = require('jsonwebtoken');
const { jwtSecretKey } = require('../config/jwtSecretKey');
const { date } = require('joi');
const { text } = require('body-parser');
/**
 * 注册接口逻辑
 **/
exports.reqisterController = (req, res) => {
    // 获取请求体数据
    const { username, password, email } = req.body;
    // 判断数据是否为空
    if (!username || !password) return res.send({ code: 1, msg: '用户名或密码不能为空' });
    // 判断用户名是否存在
    const userSql = `select * from users where username = ?`;
    db.query(userSql, [username], (err, result) => {
        // 执行sql语句失败
        if (err) return res.send({ code: 1, msg: err.message });
        //用户名存在
        if (result.length > 0) return res.send({ code: 1, msg: '用户名已存在' });
        //不存在，进行注册对密码进行加密处理
        const salt = bcrypt.genSaltSync(10);
        const hash = bcrypt.hashSync(password, salt);
        // 注册接口的逻辑
        const sql = `insert into users (username,password,email) values (?,?,?)`;
        db.query(sql, [username, hash, email], (err, result) => {
            // 执行sql语句失败
            if (err) return res.send({ code: 1, msg: err.message });
            // 注册失败
            if (result.affectedRows !== 1) return res.send({ code: 1, msg: '注册失败' });
            // 注册成功
            const data = { code: 0, msg: '注册成功', data: {
                title: '注册成功',
                code: 0,
            } }
            res.send(data);
        });
    });

};
/**
 * 登录接口逻辑
 **/
exports.loginController = (req, res) => {
    // 获取请求体数据
    const { username, password } = req.body;
    // 执行sql语句
    const loginSql = `select * from users where username =?`;
    db.query(loginSql, [username], (err, result) => {
        // 执行sql语句失败
        if (err) return res.send({ code: 1, msg: err.message });
        // 用户名不存在
        if (result.length !== 1) return res.send({ code: 1, msg: '用户名不存在' });
        // 用户名存在，判断密码是否正确
        const compareResult = bcrypt.compareSync(password, result[0].password);
        if (!compareResult) return res.send({ code: 1, msg: '密码错误' });
        // 密码正确，生成token
        const user = { ...result[0], password: '' };
        const token = jwt.sign(user, jwtSecretKey, { expiresIn: '24h' });
        // 将token响应给客户端
        res.send({ code: 0, msg: '登录成功', token: `Bearer ${token}` });
    })

};
/**
 * 用户信息查询接口逻辑
 * */
exports.userinfoController = (req, res) => {
    //获/取token
    const token = req.headers.authorization;
    //token解析
    const userinfo = jwt.verify(token.split('Bearer ')[1], jwtSecretKey);
    //将用户信息响应给客户端
    res.send({ code: 0, msg: '获取用户信息成功', data: userinfo });
};